import { HistoricalTownPortalParams as Params } from '@swda/configs/params'
import { DestinationParams as DestinationList } from '@swda/configs/params'

// 乘龙念法
let SWDA_HistoricalTownPortal = {};

Params.destinationData = [];
for (let i = 0; i < DestinationList.length; ++i) {
    const item = DestinationList[i] ;
    Params.destinationData.push(item);
};



//=============================================================================
// 回城数据类型定义
//=============================================================================
//道具技能设定部分
//1. 判定是否为传送
DataManager.isHistoricalTownPortal = function (item) {
    if (!item) return false;

    return item.meta["Historical Town Portal"] ? true : false
};

//=============================================================================
// 回城数据类型定义
//=============================================================================

function DestinationLocation(mapId, mapX, mapY) {
    this.initialize(mapId, mapX, mapY);
};

DestinationLocation.prototype.initialize = function (mapId, mapX, mapY) {
    this._mapId = mapId;
    this._mapX = mapX;
    this._mapY = mapY;
};

DestinationLocation.prototype.mapId = function () {
    return this._mapId;
};

DestinationLocation.prototype.mapX = function () {
    return this._mapX;
};

DestinationLocation.prototype.mapY = function () {
    return this._mapY;
};

//=============================================================================
// 解锁目的地
//=============================================================================

SWDA_HistoricalTownPortal.IS_MAP_LOADED = DataManager.isMapLoaded;
DataManager.isMapLoaded = function () {
    var loaded = SWDA_HistoricalTownPortal.IS_MAP_LOADED.call(this);
    if (!loaded)
        return loaded;

    SWDA_HistoricalTownPortal.loadHistoricalTownPortalData();
    return loaded;
};

SWDA_HistoricalTownPortal.loadHistoricalTownPortalData = function () {
    var map = $dataMap;
    if (!map)
        return;
    if ($testEvent)
        return;

    var reg = /<Unlock Portal: (\d*)>/;
    if (reg.exec(map.note)){
        var unlockedPortalId = Number(RegExp.$1) || 0;
        if (unlockedPortalId > 0)
            $gamePlayer._destinationUnlocked[unlockedPortalId - 1] = true;
    }
};

//=============================================================================
// 道具使用(Scene_ItemBase)
//=============================================================================

//2. 处理使用
SWDA_HistoricalTownPortal.DETERMINE_ITEM = Scene_ItemBase.prototype.determineItem;
Scene_ItemBase.prototype.determineItem = function () {
    if (DataManager.isHistoricalTownPortal(this.item())) {
        SceneManager.push(Scene_HistoricalTownPortal);
        SWDA_HistoricalTownPortal.user = this.user();
        SWDA_HistoricalTownPortal.item = this.item();
    } else {
        SWDA_HistoricalTownPortal.DETERMINE_ITEM.call(this);
    }
};


//=============================================================================
// Window_DestinationList 传送系统界面
//=============================================================================

function Window_DestinationList() {
    this.initialize.apply(this, arguments);
}

Window_DestinationList.prototype = Object.create(Window_Command.prototype);
Window_DestinationList.prototype.constructor = Window_DestinationList;

Window_DestinationList.prototype.initialize = function (helpWindow) {
    this._helpWindow = helpWindow;
    Window_Command.prototype.initialize.call(this, 336, 112);
    this.setHelpWindow(helpWindow);
};


Window_DestinationList.prototype.windowWidth = function () {
    return 608;
};

Window_DestinationList.prototype.windowHeight = function () {
    return 588;
};

Window_DestinationList.prototype.makeCommandList = function () {
    for (let i = 0; i < Params.destinationData.length; ++i) {
        // 防止新增列表时，旧档因不存在该条条目，而展示未开启的地图
        if ($gamePlayer._destinationUnlocked[i] == undefined){
            $gamePlayer._destinationUnlocked[i] = false
        }

        if ($gamePlayer._destinationUnlocked[i] === false) continue;
        const data = Params.destinationData[i];
        const ext = {
            name: data.Name,
            mapid: data.MapID,
            x: data.x,
            y: data.y,
        }

        const enabled = true;
        this.addCommand(data.Name, 'portal', enabled, ext);
    }
};


Window_DestinationList.prototype.drawItem = function (index) {
    var rect = this.itemRectForText(index);
    var align = this.itemTextAlign();
    this.resetTextColor();
    this.changePaintOpacity(this.isCommandEnabled(index));
    var name = this.commandName(index);
    this.drawText(name, rect.x, rect.y, rect.width, align);
};

Window_DestinationList.prototype.updateHelp = function () {
    if (this._helpWindow) {
        this._helpWindow.setText('请选择目的地。');
    }
};



//=============================================================================
// Scene_HistoricalTownPortal 传送系统界面
//=============================================================================

function Scene_HistoricalTownPortal() {
    this.initialize.apply(this, arguments);
}

Scene_HistoricalTownPortal.prototype = Object.create(Scene_MenuBase.prototype);
Scene_HistoricalTownPortal.prototype.constructor = Scene_HistoricalTownPortal;

Scene_HistoricalTownPortal.prototype.initialize = function () {
    Scene_MenuBase.prototype.initialize.call(this);
};

Scene_HistoricalTownPortal.prototype.create = function () {
    Scene_MenuBase.prototype.create.call(this);
    this.createHelpWindow();
    this.createDestinationListWindow();
};



Scene_HistoricalTownPortal.createHelpWindow = Scene_MenuBase.prototype.createHelpWindow;
Scene_HistoricalTownPortal.prototype.createHelpWindow = function () {
    Scene_HistoricalTownPortal.createHelpWindow.call(this)
    this._helpWindow.setBackgroundType(1)//dimmer type
    this._helpWindow.setNormalColor('#fff');
    this._helpWindow.changeTextColor(this._helpWindow.normalColor())
    this._helpWindow.x = 0;
    this._helpWindow.y = 0;
}

Scene_HistoricalTownPortal.CreateBackground = Scene_MenuBase.prototype.createBackground;
Scene_HistoricalTownPortal.prototype.createBackground = function () {
    Scene_HistoricalTownPortal.CreateBackground.call(this);
    this._backgroundSprite = new Sprite();
    const bitmap = ImageManager.loadBitmap('img/system/UI/', 'MenuBg_Destination');
    this._backgroundSprite.bitmap = bitmap;
    this.addChild(this._backgroundSprite);
}

Scene_HistoricalTownPortal.prototype.createDestinationListWindow = function () {
    this._destinationListWindow = new Window_DestinationList(this._helpWindow);
    this._destinationListWindow.opacity = 0;
    this._destinationListWindow._scrollbar.opacity = 255;
    this._destinationListWindow._scrollbar.setOffset(5);
    this.addWindow(this._destinationListWindow);
    this._destinationListWindow.setHandler('cancel', this.exitScene.bind(this));
    this._destinationListWindow.setHandler('portal', this.Portal.bind(this));
};

// 执行场景传送
Scene_HistoricalTownPortal.prototype.Portal = function () {
    var Destination = this._destinationListWindow.currentExt();
    this._destinationListWindow.activate();
    const destinationLocation = new DestinationLocation(Number(Destination.mapid), Number(Destination.x), Number(Destination.y));
    if (!destinationLocation) return;

    this.payHistoricalTownPortalCost();
    $gamePlayer.startHistoricalTownPortal();
    this.executeHistoricalTownPortal(destinationLocation);

};

Scene_HistoricalTownPortal.prototype.exitScene = function () {
    this.popScene();
};


//传送动画
SWDA_HistoricalTownPortal.playStartHistoricalTownPortalAnimation = function () {
    $gamePlayer._animationId = Params.TOWN_PORTAL_ANIMATION1;
};

SWDA_HistoricalTownPortal.playEndHistoricalTownPortalAnimation = function () {
    $gamePlayer._animationId = Params.TOWN_PORTAL_ANIMATION2;
};

//3.2 执行传送
Scene_HistoricalTownPortal.prototype.executeHistoricalTownPortal = function (destinationLocation) {
    //3.2.1 播放动画
    SceneManager.goto(Scene_Map);
    $gamePlayer.gatherFollowers();
    SWDA_HistoricalTownPortal.playStartHistoricalTownPortalAnimation();

    //3.2.3 传送开始	
    setTimeout(function (destinationLocation) {
        let mapId = destinationLocation.mapId();
        if ($gameSwitches.value(212) && mapId == 131)   //魔化韩国
            mapId = 158;
        const x = destinationLocation.mapX();
        const y = destinationLocation.mapY();
        $gamePlayer.reserveTransfer(mapId, x, y, 0, Params.TOWN_PORTAL_FADE_TYPE);
    }, Params.TOWN_PORTAL_TIMEOUT, destinationLocation);
};

//3.1 执行消耗
Scene_HistoricalTownPortal.prototype.payHistoricalTownPortalCost = function () {
    const user = SWDA_HistoricalTownPortal.user;
    const item = SWDA_HistoricalTownPortal.item;

    if (DataManager.isItem(item)) {
        SoundManager.playUseItem();
        user.consumeItem(item);
    }

    if (DataManager.isSkill(item)) {
        SoundManager.playUseSkill();
        user.paySkillCost(item);
    }
};




//=============================================================================
// Game_Player（与CP相同）
//=============================================================================
//4. 处理事后
//4.1 玩家封装一个标记，确定是否为回城传送、确定是否允许传送，封装解锁传送地点列表。
SWDA_HistoricalTownPortal.INIT_PLAYER = Game_Player.prototype.initialize;
Game_Player.prototype.initialize = function () {
    SWDA_HistoricalTownPortal.INIT_PLAYER.call(this);

    this._historicalTownPortal = false;//封装使用回城标记，隶属于【4.1】
    this._enableHistoricalTownPortal = true;//允许传送的标记，隶属于【5.1】
    this._destinationUnlocked = [];
    for (let i = 0; i < Params.destinationData.length; ++i) {
        this._destinationUnlocked.push(false);
    };
};

Game_Player.prototype.isHistoricalTownPortal = function () {
    return this._historicalTownPortal;
};

Game_Player.prototype.startHistoricalTownPortal = function () {
    this._historicalTownPortal = true;
};

Game_Player.prototype.endHistoricalTownPortal = function () {
    this._historicalTownPortal = false;
};

Game_Player.prototype.unlockAllDestinations = function () {
    for (let i = 0; i < this._destinationUnlocked.length; ++i) {
        this._destinationUnlocked[i] = true;
    };
};

//4.2 执行传送后动画
SWDA_HistoricalTownPortal.PERFORM_TRANSFER = Game_Player.prototype.performTransfer;
Game_Player.prototype.performTransfer = function () {
    SWDA_HistoricalTownPortal.PERFORM_TRANSFER.call(this);

    if (this.isHistoricalTownPortal()) {
        SWDA_HistoricalTownPortal.playEndHistoricalTownPortalAnimation();
        setTimeout(function (player) {
            player.endHistoricalTownPortal();
        }, Params.TOWN_PORTAL_TIMEOUT, this);
    }
};


//=============================================================================
// 5. 回城技能道具使用条件以及禁止回城模式
//=============================================================================

//5.1 禁止传送模式标记
Game_Player.prototype.canHistoricalTownPortal = function () {
    return this._enableHistoricalTownPortal;
};

Game_Player.prototype.enableHistoricalTownPortal = function () {
    this._enableHistoricalTownPortal = true;
};

Game_Player.prototype.disableHistoricalTownPortal = function () {
    this._enableHistoricalTownPortal = false;
};

//5.2 技能物品使用条件
SWDA_HistoricalTownPortal.TOWN_PORTAL_CAN_USE = Game_BattlerBase.prototype.canUse;
Game_BattlerBase.prototype.canUse = function (item) {
    var canUse = SWDA_HistoricalTownPortal.TOWN_PORTAL_CAN_USE.call(this, item);
    if (DataManager.isHistoricalTownPortal(item)) {
        if (!SWDA_HistoricalTownPortal.mapCanTownPortal())//地图禁止回城
            canUse = false;
        if (!$gamePlayer.canHistoricalTownPortal())//事件禁止回城
            canUse = false;
        if ($gameParty.inBattle())//战斗中禁止回城
            canUse = false;
    }
    return canUse;
};


//5.2.1 地图传送条件：没有<Can Historical Portal>标签的地图禁止传送
SWDA_HistoricalTownPortal.mapCanTownPortal = function () {
    if (!$dataMap)
        return false;
    var canTownPortal = $dataMap.meta["Can Historical Portal"];

    if (!canTownPortal)
        return false;

    return true;
};

//5.2.2 禁止传送状态指定：插件命令EnableHistoricalPortal与DisableHistoricalPortal
SWDA_HistoricalTownPortal.PLUGIN_COMMAND = Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function (command, args) {
    SWDA_HistoricalTownPortal.PLUGIN_COMMAND.call(this, command, args);

    if (command == 'EnableHistoricalPortal')
        $gamePlayer.enableHistoricalTownPortal();
    if (command == 'DisableHistoricalPortal')
        $gamePlayer.disableHistoricalTownPortal();
};

//=============================================================================
// 6. 移动控制：为了防止在传送过程中因移动触发事件而导致不可预知的BUG，传送过程中禁止移动
//=============================================================================
//6.1 禁止玩家移动
SWDA_HistoricalTownPortal.PLAYER_CAN_MOVE = Game_Player.prototype.canMove;
Game_Player.prototype.canMove = function () {
    var canMove = SWDA_HistoricalTownPortal.PLAYER_CAN_MOVE.call(this);
    if ($gamePlayer.isHistoricalTownPortal())
        canMove = false;
    return canMove;
};

//6.2 禁止事件移动
SWDA_HistoricalTownPortal.UPDATE_EVENT_MOVEMENT = Game_Event.prototype.updateSelfMovement;
Game_Event.prototype.updateSelfMovement = function () {
    if (!$gamePlayer.isHistoricalTownPortal())
        SWDA_HistoricalTownPortal.UPDATE_EVENT_MOVEMENT.call(this);
};
